// pages/recording/recording.js
// 导入HTTP请求工具类
const { http } = require('../../utils/http');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'practice',
    examRecords: [], 
    practiceRecords: [], 
    pastRecords: [], // 历年真题记录数组
    loading: false, // 加载状态
    errorMsg: '' // 错误信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 优先从页面参数中获取recordType，如果没有则使用默认值
    const recordType = options.recordType || this.data.activeTab;
    this.setData({ activeTab: recordType });
    this.fetchDataByTab(recordType);
  },

  /**
   * 切换记录类型标签
   */
  switchTab(e) {
    const recordType = e.currentTarget.dataset.type;
    if (this.data.activeTab === recordType) return; // 避免重复加载
    
    this.setData({
      activeTab: recordType,
      errorMsg: '' // 清空错误信息
    });
    this.fetchDataByTab(recordType);
  },

  /**
   * 根据记录类型获取对应数据
   * @param {string} recordType - 记录类型 (exam/practice/past)
   */
  fetchDataByTab(recordType) {
    this.setData({ loading: true });
    
    // 映射记录类型到数据键名和接口参数
    const typeConfig = {
      exam: { dataKey: 'examRecords' },
      practice: { dataKey: 'practiceRecords' },
      past: { dataKey: 'pastRecords' }
    };
    // 默认使用练习记录配置
    const { dataKey } = typeConfig[recordType] || typeConfig.practice;
    const typeParam = recordType in typeConfig ? recordType : 'practice';
    
    this.fetchRecords(dataKey, typeParam);
  },

  /**
   * 从接口获取记录数据
   * @param {string} dataKey - 数据存储键名
   * @param {string} typeParam - 接口查询类型参数
   */
  fetchRecords(dataKey, typeParam) {
    const apiUrl = '/wjq/answerrecord/listWithBank';
    const params = { type: typeParam };
    
    console.log('获取记录数据:', { apiUrl, params });
    http.get(apiUrl, params)
      .then(res => {
        this.setData({ loading: false });
        const rows = this.parseResponseData(res);
        const filteredRows = this.filterRecords(rows, typeParam);
        const formattedData = filteredRows.map(record => this.formatRecord(record));
        
        this.setData({ [dataKey]: formattedData });
      })
      .catch(err => {
        this.setData({ 
          loading: false,
          errorMsg: err.message || '获取数据失败',
          [dataKey]: []
        });
        wx.showToast({ title: err.message || '获取数据失败', icon: 'none' });
        console.error('获取记录失败:', err);
      });
  },

  /**
   * 解析接口响应数据，兼容多种返回格式
   * @param {Object} res - 接口响应数据
   * @returns {Array} 提取的记录数组
   */
  parseResponseData(res) {
    if (!res) return [];
    
    // 优先匹配常见的接口返回格式
    const possiblePaths = [
      'data.rows',
      'rows',
      'data',
      'data.data.rows'
    ];
    
    for (const path of possiblePaths) {
      const value = path.split('.').reduce((obj, key) => obj?.[key], res);
      if (Array.isArray(value)) return value;
    }
    
    return [];
  },

  /**
   * 根据类型过滤记录
   * @param {Array} rows - 原始记录数组
   * @param {string} typeParam - 过滤类型
   * @returns {Array} 过滤后的记录数组
   */
  filterRecords(rows, typeParam) {
    const typeMap = {
      exam: '模拟考试',
      practice: '章节训练',
      past: '院校真题'
    };
    const targetType = typeMap[typeParam];
    if (!targetType) return rows;
    
    return rows.filter(record => {
      const recordType = record.record_type || record.recordType;
      return recordType === targetType;
    });
  },

  /**
   * 格式化单条记录数据
   * @param {Object} record - 原始记录
   * @returns {Object} 格式化后的记录
   */
  formatRecord(record) {
    // 计算正确率
    const totalCount = record.total_count || record.totalCount || 0;
    const correctList = record.correct_list || record.correctList || '';
    const correctCount = this.getListLength(correctList);
    const progress = totalCount > 0 ? `${Math.round((correctCount / totalCount) * 100)}%` : '0%';
    
    return {
      id: record.id || '',
      title: this.getRecordTitle(record),
      progress,
      time: this.formatTime(record),
      date: this.formatDate(record),
      originalRecord: record // 保留原始数据用于跳转
    };
  },

  /**
   * 获取记录标题（优先使用题库名，无则使用类型默认名）
   * @param {Object} record - 原始记录
   * @returns {string} 格式化后的标题
   */
  getRecordTitle(record) {
    // 尝试从根级字段获取标题
    const titleFields = [
      'bankName', 'bank_name', 'tiku_name', 'questionBankName',
      'question_bank_name', 'tikuName', 'examName', 'practiceName',
      'title', 'examTitle', 'practiceTitle'
    ];
    for (const field of titleFields) {
      if (record[field]) return record[field];
    }
    
    // 尝试从嵌套对象获取标题
    if (record.questionBank?.name) return record.questionBank.name;
    if (record.questionBank?.title) return record.questionBank.title;
    
    // 使用类型默认标题
    const recordType = record.record_type || record.recordType;
    const typeTitles = {
      '模拟考试': '未命名考试',
      '章节训练': '未命名练习',
      '院校真题': '未命名历年真题'
    };
    return typeTitles[recordType] || recordType || '无标题记录';
  },

  /**
   * 格式化时间（秒转分钟或使用接口返回的字符串）
   * @param {Object} record - 原始记录
   * @returns {string} 格式化后的时间
   */
  formatTime(record) {
    // 优先使用接口返回的格式化时间
    if (record.time_used_str) return record.time_used_str;
    if (record.timeUsedStr) return record.timeUsedStr;
    
    // 转换秒为分钟
    const seconds = record.time_used || record.timeUsed || 0;
    return `${Math.floor(seconds / 60)}分钟`;
  },

  /**
   * 格式化日期
   * @param {Object} record - 原始记录
   * @returns {string} 日期字符串
   */
  formatDate(record) {
    return record.create_time || record.createTime || '';
  },

  /**
   * 获取列表长度（兼容数组和字符串格式）
   * @param {Array|string} list - 列表数据
   * @returns {number} 列表长度
   */
  getListLength(list) {
    if (Array.isArray(list)) return list.length;
    return list.toString()
      .split(',')
      .map(id => id.trim())
      .filter(id => id)
      .length;
  },

  /**
   * 重试加载数据
   */
  retryLoad() {
    this.setData({ errorMsg: '' });
    this.fetchDataByTab(this.data.activeTab);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.fetchDataByTab(this.data.activeTab);
  },

  /**
   * 点击记录标题跳转到答题报告页面
   */
  onRecordTitleTap(e) {
    const record = e.currentTarget.dataset.record;
    if (!record.id) {
      wx.showToast({ title: '记录信息不完整，无法查看详情', icon: 'none' });
      return;
    }
    
    // 构建报告数据
    const reportData = this.buildReportData(record, record.originalRecord || {});
    const recordId = record.id;
    const bankId = reportData.questionBankId;
    
    try {
      // 保存练习报告到本地存储作为备份
      const storageKey = `answerReport_recording_${recordId}`;
      wx.setStorageSync(storageKey, reportData);
    } catch (e) {
      console.error('保存练习报告失败:', e);
    }
    
    // 构建URL
    let url = `/index/pages/answerReport/answerReport?id=${recordId}`;
    if (bankId) url += `&bankId=${bankId}`;
    url += `&reportData=${encodeURIComponent(JSON.stringify(reportData))}`;
    
    // 跳转到答题详情页面
    wx.navigateTo({
      url,
      success: () => {
        console.log('跳转到答题详情页面成功', { recordId, bankId });
      },
      fail: (err) => {
        console.error('跳转到答题详情页面失败:', err);
        // 如果跳转失败，显示弹窗作为备选方案
        const practiceTime = this.formatTime(record.originalRecord);
        wx.showModal({
          title: `${record.title} 详情`,
          content: `练习时间: ${practiceTime}\n状态: 已完成`,
          showCancel: false,
          confirmText: '确定'
        });
      }
    });
  },


  /**
   * 构建报告数据
   * @param {Object} record - 格式化后的记录
   * @param {Object} originalRecord - 原始记录
   * @returns {Object|null} 报告数据对象
   */
  buildReportData(record, originalRecord) {
    // 提取基础数据
    const totalCount = originalRecord.total_count || originalRecord.totalCount || 0;
    const [correctArray, correctCount] = this.parseList(originalRecord.correct_list || originalRecord.correctList);
    const [wrongArray, wrongCount] = this.parseList(originalRecord.wrong_list || originalRecord.wrongList);
    const [unansweredArray, unansweredCount] = this.parseList(originalRecord.unanswered_list || originalRecord.unansweredList);
    
    // 构建题目ID映射和状态
    const { questionIdMap, enhancedAnswerStatus } = this.buildQuestionStatusMap(
      correctArray, wrongArray, unansweredArray
    );
    
    return {
      id: record.id,
      total: totalCount,
      correct: correctCount,
      wrong: wrongCount,
      unanswered: unansweredCount,
      questionBankName: record.title,
      questionBankId: originalRecord.bank_id || originalRecord.bankId || '',
      totalTime: originalRecord.time_used || originalRecord.timeUsed || 0,
      completeTime: originalRecord.create_time || originalRecord.createTime || '',
      recordType: originalRecord.record_type || originalRecord.recordType || '',
      correctList: originalRecord.correct_list || originalRecord.correctList || '',
      wrongList: originalRecord.wrong_list || originalRecord.wrongList || '',
      unansweredList: originalRecord.unanswered_list || originalRecord.unansweredList || '',
      questionIdMap,
      enhancedAnswerStatus
    };
  },

  /**
   * 解析列表数据（兼容数组和字符串格式，去除引号）
   * @param {Array|string} list - 原始列表数据
   * @returns {[Array, number]} [处理后的数组, 长度]
   */
  parseList(list) {
    if (!list) return [[], 0];
    
    const array = Array.isArray(list) 
      ? list 
      : list.toString()
          .split(',')
          .map(id => id.trim()
                       .replace(/^"|"$/g, '') 
                       .replace(/^\[|\]$/g, '')) 
          .filter(id => id);
    
    return [array, array.length];
  },

  /**
   * 构建题目ID映射和状态映射
   * @param {Array} correctArray - 正确题目ID数组
   * @param {Array} wrongArray - 错误题目ID数组
   * @param {Array} unansweredArray - 未答题目ID数组
   * @returns {Object} 包含映射关系的对象
   */
  buildQuestionStatusMap(correctArray, wrongArray, unansweredArray) {
    const questionIdMap = {};
    const enhancedAnswerStatus = {};
    let index = 0;
    
    // 处理正确题目
    index = this.fillQuestionMap(correctArray, 'correct', index, questionIdMap, enhancedAnswerStatus);
    // 处理错误题目
    index = this.fillQuestionMap(wrongArray, 'wrong', index, questionIdMap, enhancedAnswerStatus);
    // 处理未答题目
    this.fillQuestionMap(unansweredArray, 'unanswered', index, questionIdMap, enhancedAnswerStatus);
    
    return { questionIdMap, enhancedAnswerStatus };
  },

  /**
   * 填充题目映射关系
   * @param {Array} ids - 题目ID数组
   * @param {string} status - 题目状态
   * @param {number} startIndex - 起始索引
   * @param {Object} idMap - ID映射对象
   * @param {Object} statusMap - 状态映射对象
   * @returns {number} 结束索引
   */
  fillQuestionMap(ids, status, startIndex, idMap, statusMap) {
    let index = startIndex;
    ids.forEach(id => {
      idMap[index] = id;
      statusMap[index] = { questionId: id, status };
      index++;
    });
    return index;
  },

  // 以下生命周期函数保留空实现，便于后续扩展
  onReady() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
});